package com.example.springbootshiro.shiro;

import com.example.springbootshiro.model.Permission;
import com.example.springbootshiro.model.Role;
import com.example.springbootshiro.model.User;
import com.example.springbootshiro.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

//import org.apache.shiro.authc.*;

public class AuthRealm extends AuthorizingRealm
{
    @Autowired
    private UserService userService;

    /**
     * 授权方法
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection)
    {
        //从Session中获取用户信息
        Collection<User> collection=principalCollection.fromRealm(this.getClass().getName());
        User user=collection.iterator().next();

        List<String> permissionList=new ArrayList<>();

        List<String> roleNameList=new ArrayList<>();

        Set<Role> roleSet=user.getRoles();

        if(CollectionUtils.isEmpty(roleSet))
        {
            for(Role role : roleSet)
            {
                roleNameList.add(role.getName());

                Set<Permission> permissionSet=role.getPermissions();

                if(CollectionUtils.isEmpty(permissionSet))
                {
                    for(Permission permission : permissionSet)
                    {
                        permissionList.add(permission.getName());
                    }
                }
            }
        }

        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();

        simpleAuthorizationInfo.addStringPermissions(permissionList);

        simpleAuthorizationInfo.addRoles(roleNameList);

        return simpleAuthorizationInfo;
    }

    /**
     * 认证登录方法
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws
            AuthenticationException
    {
        //强转成用户名和密码登录token
        UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken) authenticationToken;
        //从token中取出用户名
        String userName=usernamePasswordToken.getUsername();
        //从数据库中获取用户
        User user=this.userService.findByUsername(userName);
        //返回认证信息
        return new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
    }
}
